<template>
	<view class="page">
		<block v-if="wordList.length>0">
			<view class="nav d_flex_b" v-if="groupList.length>0">
				<view class="box1 break-words whitespace-pre-line" style="width: 450rpx;"><text style="margin-right: 10rpx;">{{groupList[curGroup].name}} </text> <text
						v-if="groupList.length-1==curGroup&&current==wordList.length">{{current}}</text><text
						v-else>{{current+1}}</text>/{{groupList[curGroup].total-groupList[curGroup].graspTotal}}</view>
				<view class="box2 d_flex_b" v-if="!(groupList.length-1==curGroup&&current==wordList.length)">
          <Signature :signatureTop="upx2px(96)" />
          <view class="pl-20"></view>
          <view class="label">默记</view>
					<u-switch v-model="value" size="20" activeColor="#5480F8" inactiveColor="#e4e5ec"></u-switch>
				</view>
			</view>
			<view v-else class="nav d_flex_b">
				<view class="box1 break-words whitespace-pre-line" style="width: 450rpx;">
          <text style="margin-right: 10rpx;">{{title}} </text>
          <text v-if="current==wordList.length">{{current}}</text>
          <text v-else>{{current+1}}</text>/{{wordList.length}}
        </view>
				<view class="box2 d_flex_b" v-if="current!=wordList.length">
          <Signature :signatureTop="upx2px(96)" />
          <view class="pl-20"></view>
					<view class="label">默记</view>
					<u-switch v-model="value" size="20" activeColor="#5480F8" inactiveColor="#e4e5ec"></u-switch>
				</view>
			</view>
			<swiper class="swiper-box" :current="current" @change="changeCurrent" v-if="isInit">
				<swiper-item v-for="(val,i) in wordList" :key="val.id">
					<scroll-view v-if="i == current || i == current + 1 || i == current - 1" class="swiper-item" scroll-y="true">
						<view class="content d_flex_c" v-if="value">
							<view class="collect" @click="collectHandle(val)">
								<image v-if="!val.favorite" src="/static/star1.png" mode=""></image>
								<image v-else src="/static/star.png" mode=""></image>
							</view>
							<view class="word">{{val.name}}</view>
						</view>
						<view class="content" v-else>
							<view class="collect" @click="collectHandle(val)">
								<image v-if="!val.favorite" src="/static/star1.png" mode=""></image>
								<image v-else src="/static/star.png" mode=""></image>
							</view>
							<view class="box">
								<view class="word-i">{{val.name}}</view>
								<wordphonetic :data="val" :isSpell="true"></wordphonetic>
								<wordexplain :data="val.explain" :parentData="val"></wordexplain>
								<view class="memory" v-if="val.mnemonic.length>0">
									<view class="con">
										<view v-for="(item,i) in val.mnemonic" :key="i">
                      {{item.mnemonicMethodName}}{{item.name}}
										</view>
									</view>
								</view>
								<view class="explan" v-if="val.exampleSentence.length>0">
									<view class="tit">例句：</view>
									<view class="ex-item" v-for="(item,i) in val.exampleSentence" :key="i">
										<view class="qes">
											<image style="display: inline-block;"  v-if="item.trueQuestion" src="/static/zt.png" mode=""></image>
											<rich-text :class="item.trueQuestion?'ac':''" v-if="item.example" :nodes="item.example"></rich-text>
										</view>
										<view class="ans">
											{{item.chinExplain||''}} {{ item.subjectName }} {{ item.publishDate }}
										</view>
									</view>
								</view>
								<view class="el-item" v-if="val.affixes.length>0">
									<view class="tit">词根词缀：</view>
									<view class="con">
										<view v-for="(item,i) in val.affixes" :key="i">
											{{item.name}} {{item.chinExplain}}
										</view>
									</view>
								</view>
								<view class="el-item" v-if="val.phrases.length>0">
									<view class="tit">固定搭配：</view>
									<view class="con" >
										<view v-for="(item,i) in val.phrases" :key="i">
											<text>{{item.name||''}}</text>
											<text style="margin-left: 10rpx;">{{item.chineseExplain||''}}</text>
										</view>
									</view>
								</view>
								<view class="word-err" @click="wordErr">单词报错</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
			<view class="page-btn flex" v-if="current<wordList.length">
				<view class="btn flex-2 mr-40" @click="openGrasp">已掌握</view>
				<view class="btn flex-1" @click="submit(2)">不确定</view>
			</view>
			<view class="guide" v-if="guide">
				<image src="/static/gu1.png" mode=""></image>
				<view class="btn" @click="closeGuide">知道了</view>
			</view>
		</block>
		<block v-if="isInit&&isOver==1">
			<view class="swiper-item">
				<view class="over">
					<image src="/static/over.png" mode=""></image>
					<view class="txt">恭喜你，今日任务已完成~</view>
					<view class="btn" @click="toIndex">回首页</view>
				</view>
			</view>
		</block>
		<block v-if="isInit&&isOver==2">
			<view class="swiper-item">
				<view class="over">
					<image src="/static/over.png" mode=""></image>
					<view class="txt">恭喜你，此词书已全部学完</view>
					<view class="btn" @click="toIndex">回首页</view>
				</view>
			</view>
		</block>
		<uni-popup ref="popup" type="center">
			<view class="tip-pop">
				<view class="txt">标记已掌握的单词将不再练习，是否确认标记？</view>
				<view class="tip d_flex_c" @click="isTip=!isTip">
					<image v-if="!isTip" src="/static/radio.png" mode=""></image>
					<image v-else src="/static/suc.png" mode=""></image>
					<text>不再提示</text>
				</view>
				<view class="btn-box d_flex_b">
					<view class="btn" @click="cancel">取消</view>
					<view class="btn ac" @click="submit">确认</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="nextPop" type="center" :is-mask-click="false">
			<view class="tip-pop text-center">
				<view v-if="isGroup" class="tip">
          <view v-if="isAllGroupFinish">恭喜你，此词书已全部学完</view>
          <view v-else>本组任务已完成，是否继续学习下一组？</view>
        </view>
				<view v-else class="tip">当日任务已完成</view>
				<view class="btn-box flex justify-center items-center">
					<view class="btn" @click="toIndex">回首页</view>
          <view class="pl-10"></view>
					<view v-if="isGroup && !isAllGroupFinish" class="btn ac" @click="next">我要继续</view>
				</view>
			</view>
		</uni-popup>
		
	</view>
</template>

<script>
	import {toneMaps} from '@/util/status.js'
  import {handleExampleSentence} from "@/util/bizUtil";

  export default {
		data() {
			return {
				toneMaps:toneMaps,
				value: false,
				star: false,
				isOver: 0,
				guide: false,
				isTip: false,
				groupList: [],
				curGroup: 0,
				traceId: '',
				wordList: [],
				current: 0,
				isInit: false,
				title: '',
				tIsover:false,
				isUpdate:false,
				innerAudioContext:'',
        groupId: 0,
        isGroup: 0,
			};
		},
    computed: {
      // 本组或者当日计划是否已完成(0:否,1:是)
      finish() {
        if (this.isGroup == 1) {
          const group = this.groupList[this.curGroup]
          if (group?.total - group?.graspTotal === this.current + 1) {
            return 1
          }
        } else {
          if (this.wordList.length === this.current + 1) {
            return 1
          }
        }
        return 0
      },
      // 是否所有分组已背完
      isAllGroupFinish() {
        const group = this.groupList?.at(-1)
        return this.groupId == group?.groupId && this.finish
      },
    },
		onLoad(e) {
			this.innerAudioContext = uni.createInnerAudioContext();
			this.innerAudioContext.onError(res => {
				console.log(res.errMsg);
				console.log(res.errCode);
			});
			if (!uni.getStorageSync('isHasRemember')) {
				this.guide = true;
			}
			this.isTip = uni.getStorageSync('userMoreData').notTips||false;
			this.id = e.id;
			this.isGroup = Number(e.isGroup);
			this.groupId = Number(e.groupId) || 0;
			// console.log('e.tit',e.tit,decodeURIComponent(e.tit))
			this.title = e.tit ? decodeURIComponent(decodeURIComponent(e.tit)) : '';
		},
		onShow() {
			if(!this.isUpdate){
				if (this.isGroup != 1) {
					this.getWordList();
				} else {
					this.getGroup();
				}
			}else{
				this.isUpdate=false;
			}
		},
		methods: {
      upx2px(v) {
        return uni.upx2px(v)
      },
			handleTip() {
				// this.isTip = !this.isTip;
				// uni.setStorageSync('isTip', true);
			},
			getGroup() {
				uni.showLoading()
				this.$http.get1('/api/client/word/listWordGroupInfo', {
					bookId: this.id
				}).then(res => {
					uni.hideLoading()
					if (res.code == 200) {
						this.groupList = res.data;
						this.traceId = res.traceId;
						if (res.data.length > 0) {
							console.log('this.groupId=',this.groupId);
							if (this.groupId) {
								this.getWordList(this.groupId);
								this.curGroup = this.groupList.findIndex((element) => element.groupId == this.groupId) || 0;
								console.log(this.curGroup)
							} else {
								let arr=this.groupList.filter(val=>{
									return val.graspTotal<val.total
								})
								if(arr.length>0){
									this.curGroup = this.groupList.findIndex((element) => element.groupId == arr[0].groupId) || 0;
									this.getWordList(arr[0].groupId);
								}else{
									this.isOver=2;//词书全部学完
									this.isInit = true;
								}
								
							}
						} else {
							this.isInit = true;
						}
					}
				})
			},
			getWordList(gid) {
				let obj = {
					publishDate: this.timeCycle(new Date()),
					filter: true,
					groupId: '',
				};
				if (gid) {
          this.groupId = gid
					obj.groupId = gid;
				}
				this.$http.get1('/api/client/word/memory', obj).then(res => {
					if (res.code == 200) {
						this.current = 0;
						this.wordList = res.data.map((val,index)=>{
							val.explain=val.wordExplain?JSON.parse(val.wordExplain):[];
							handleExampleSentence(val)
							return val;
						});
						this.isInit = true;
						if(res.data.length==0){
              if (this.isGroup) {
                this.isOver=2
              } else {
                const book = uni.getStorageSync('curBook')
                if (book?.graspTotal >= book?.total) {
                  this.isOver = 2
                } else {
                  this.isOver = 1
                }
              }
						}
					}
				})
			},
			//查询当前组是否全部学完
			checkWordList(){
				return new Promise((resolve)=>{
					let obj = {
						publishDate: this.timeCycle(new Date()),
						filter: true,
						groupId: '',
					};
					if (this.groupList.length>0&&this.groupList[this.curGroup].groupId) {
						obj.groupId = this.groupList[this.curGroup].groupId;
					}
					this.$http.get1('/api/client/word/memory', obj).then(res => {
						if (res.code == 200) {
							if(res.data.length==0){
								this.$refs.nextPop.open();
							}else{
								resolve()
							}
						}
					})
					
				})

			},
			closeGuide() {
				this.guide = false;
				uni.setStorageSync('isHasRemember', true)
			},
			collectHandle(val) {
				val.favorite = !val.favorite;
				this.$http.get1('/api/client/word/favoritesUpdate', {
					wordBookId: this.id,
					wordId: val.id,
					action: val.favorite ? '1' : '0'
				}).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '操作成功'
						})
					}
				})
			},
			wordErr() {
				this.isUpdate=true;
				uni.navigateTo({
					url: '/pagesA/pages/test/word-error?id=' + this.wordList[this.current].id + '&word=' + this.wordList[this.current].name
				})
			},
			openGrasp() {
				if (this.isTip) {
					this.submit();
				} else {
					this.$refs.popup.open();
				}
			},
			cancel() {
				this.isTip=false;
				this.$refs.popup.close();
			},
			changeCurrent(e) {
				this.current = e.detail.current;
			},
			setTip(){
				this.$http.post('qh/user/setMemoryWordTips',{
					notTips:1
				}).then(res=>{
					let userMoreData=uni.getStorageSync('userMoreData');
					if(userMoreData){
						userMoreData.notTips=1;
					}else{
						userMoreData={
							notTips:1
						};
					}
					
					uni.setStorageSync('userMoreData')
				})
			},
			submit(grasp=1) {
				if(this.isTip){
					this.setTip();
				}
				let obj = {
					wordId: this.wordList[this.current].id,
					publishDate: this.$tool.getCurrentTime(),
          finish: this.finish,
          grasp: grasp,
					groupId: ''
				};
				console.log('this.isGroup=',this.isGroup);
				if (this.isGroup==1) {
					obj.groupId = this.groupList[this.curGroup].groupId
				}
				this.$http.put('/api/client/word/graspWord', obj, 0, 'application/json').then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '操作成功'
						});
						if (this.current < this.wordList.length - 1) {
							this.current++;
						} else {
							// if (this.curGroup < this.groupList.length - 1) {
							// 	this.$refs.nextPop.open();
							// } else {
							// 	this.current++;
							// }
						}
						
						if(grasp==1) {
						this.checkWordList();
						}else {
							// 点击不确定,刷新列表
							if(this.isGroup==1){
								this.getWordList(this.groupId);
							}else{
								this.getWordList()
							}
						}
						
						this.$refs.popup.close();
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}
				})
			},
			toIndex() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			next() {
				this.curGroup++;
				this.$refs.nextPop.close();
				if(this.groupId){
					this.getWordList(this.groupList[this.curGroup].groupId);
				}else{
					this.getWordList()
				}
			},
			//拼读
			spell(item) {
        this.innerAudioContext.autoplay = true
				let that = this;
				this.$http
					.gettts('api/client/word/tts', {
						wordStr: item.name,
						langType: 'en'
					})
					.then(res => {
						const fs = wx.getFileSystemManager();
						const basePath = `${wx.env.USER_DATA_PATH}/audio`;
						const audioPath = `${basePath}/${new Date().getTime()}.mp3`;
						let hasFolder = true;
						try {
							fs.accessSync(basePath);
						} catch (e) {
							hasFolder = false;
						}
						// 没有则先创建audio文件夹
						if (!hasFolder) {
							fs.mkdir({
								dirPath: basePath
							});
						}
						fs.writeFile({
							filePath: audioPath,
							data: res,
							encoding: 'binary',
							success: res => {
								that.innerAudioContext.src = audioPath;
								that.innerAudioContext.onPlay(() => {
									console.log('开始播放');
								});
							}
						});
					});
			},
			timeCycle(value, type) {
				if (value) {
					var dd = new Date(value);
					var y = dd.getFullYear();
					var m = dd.getMonth() + 1;
					var d = dd.getDate();
					var h = dd.getHours();
					var i = dd.getMinutes();
					var s = dd.getSeconds();
					m = m < 10 ? '0' + m : m;
					d = d < 10 ? '0' + d : d;
					h = h < 10 ? '0' + h : h;
					i = i < 10 ? '0' + i : i;
					s = s < 10 ? '0' + s : s;
					if (type == 1) {
						return y + '-' + m + '-' + d + ' ' + h + ':' + i + ':' + s
					} else if (type == 2) {
						return y + '-' + m + '-' + d + ' ' + h + ':' + i
					} else if (type == 3) {
						return m + '/' + d
					} else if (type == 4) {
						return y + '.' + m + '.' + d
					} else {
						return y + '-' + m + '-' + d
					}
				}
			},

		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F2F3F8;
	}

	.page {
		padding: 120rpx 0 200rpx;
		box-sizing: border-box;
	}

	.nav {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 96rpx;
		z-index: 9;
		background-color: #fff;
		padding: 0 30rpx;
		box-sizing: border-box;

		.box1 {
			font-size: 28rpx;
			color: #575A64;
		}

		.box2 {
			font-size: 28rpx;
			color: #333333;

			.label {
				margin-right: 20rpx;
			}
		}
	}

	.swiper-box {
		min-height: calc(100vh - 310rpx);
		
	}

	.swiper-item {
		height: calc(100vh - 310rpx);
		border-radius: 20rpx;
		overflow: hidden;
		padding: 0 30rpx;
	}

	.content {
		min-height: calc(100vh - 310rpx);
		background-color: #fff;
		box-shadow: 0rpx 4rpx 8rpx 2rpx rgba(42, 65, 152, 0.05);
		border-radius: 20rpx;
		box-sizing: border-box;
		padding: 0 30rpx;
		position: relative;
		display: flex;
		justify-content: center;

		.collect {
			position: absolute;
			top: 30rpx;
			right: 30rpx;

			image {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.word {
			font-size: 60rpx;
			font-weight: 800;
			color: #333333;
			text-align: center;
		}

		.box {
			width: 100%;
			padding: 30rpx 0;
			box-sizing: border-box;

			.word-i {
				font-size: 60rpx;
				font-weight: 800;
				color: #333333;
			}

			.spring {
				font-size: 28rpx;
				color: #575A64;
				margin: 20rpx 0;

				image {
					position: relative;
					// top: 6rpx;
					width: 32rpx;
					height: 32rpx;
					margin-left: 20rpx;
				}
			}

			.mean {
				font-size: 28rpx;
				color: #575A64;
				margin-bottom: 20rpx;
			}

			.memory {
				padding-bottom: 30rpx;
				border-bottom: 1rpx solid #E4E5EC;

				.label {
					font-size: 28rpx;
					font-weight: bold;
					color: #575A64;
					margin-bottom: 20rpx;
				}

				.con {
					background: rgba(84, 128, 248, 0.05);
					border-radius: 10rpx;
					border: 1rpx dashed #5480F8;
					font-size: 24rpx;
					color: #575A64;
					padding: 20rpx;
					box-sizing: border-box;
					line-height: 1.8;
				}
			}

			.explan {
				padding: 30rpx 0 10rpx;
				border-bottom: 1rpx solid #E4E5EC;

				.tit {
					font-size: 32rpx;
					font-weight: bold;
					color: #333333;
				}

				.ex-item {
					.qes {
						margin: 20rpx 0 10rpx;
						position: relative;
						image {
							position: absolute;
							top: 2rpx;
							left: 0;
							margin-right: 8rpx;
							width: 60rpx;
							height: 32rpx;
							display: inline-block;
						}
						rich-text{
							// display: inline-block;
							line-height: 1.2;
							font-size: 30rpx;
							&.ac{
								text-indent: 2.5em;
							}
						}
						
					}

					.ans {
						font-size: 28rpx;
						color: #575A64;
						margin-bottom: 20rpx;
					}
				}
			}

			.el-item {
				.tit {
					font-size: 32rpx;
					font-weight: bold;
					color: #333333;
				}

				padding-top: 20rpx;
				border-bottom: 1rpx solid #E4E5EC;

				.con {
					margin: 20rpx 0 30rpx;

					text {
						color: #999;
						font-size: 28rpx;
					}
				}
			}

			.word-err {
				margin-top: 30rpx;
				text-align: center;
				line-height: 48rpx;
				width: 136rpx;
				height: 48rpx;
				border-radius: 46rpx;
				border: 2rpx solid #BBBFCC;
				font-size: 24rpx;
				color: #575A64;
			}
		}


	}

	.over {
		height: calc(100vh - 350rpx);
		text-align: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		image {
			width: 286rpx;
			height: 360rpx;
		}

		.txt {
			margin: 20rpx 0 40rpx;
			font-size: 32rpx;
			color: #575A64;
		}

		.btn {
			margin: 0 auto;
			width: 510rpx;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 46rpx;
			border: 2rpx solid #5480F8;
			text-align: center;
			font-size: 32rpx;
			font-weight: 500;
			color: #5480F8;
		}
	}

	.page-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 176rpx;
		padding: 30rpx 62rpx;
		box-sizing: border-box;
		background-color: #fff;
		z-index: 10;

		.btn {
			width: 100%;
			height: 90rpx;
			background: #5480F8;
			border-radius: 46rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 32rpx;
			font-weight: 500;
			color: #FFFFFF;

			&.disable {
				background-color: #CAD8FC;
			}
		}
	}

	.guide {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 30;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		image {
			width: 280rpx;
			height: 222rpx;
			margin-bottom: 30rpx;
		}

		.btn {
			width: 626rpx;
			height: 90rpx;
			line-height: 90rpx;
			background: #5480F8;
			border-radius: 46rpx;
			font-size: 32rpx;
			font-weight: 500;
			color: #fff;
			text-align: center;
		}
	}

	.tip-pop {
		width: 590rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 60rpx 40rpx 40rpx;
		box-sizing: border-box;

		.txt {
			font-size: 32rpx;
			font-weight: 500;
			color: #333333;
			margin-bottom: 30rpx;
			line-height: 1.8;
		}

		.tip {
			font-size: 24rpx;
			color: #333333;
			margin-bottom: 30rpx;

			image {
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}
		}

		.btn-box {
			.btn {
				width: 240rpx;
				height: 90rpx;
				border-radius: 46rpx;
				border: 2rpx solid #5480F8;
				text-align: center;
				line-height: 90rpx;
				color: #5480F8;
				font-size: 32rpx;
				font-weight: 500;

				&.ac {
					background-color: #5480F8;
					color: #fff;
				}
			}
		}
	}
</style>